package com.xbhog.transaction.jdbc;

import com.xbhog.session.TransactionIsolationLevel;
import com.xbhog.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @author 衣立君
 * @date 2024/03/13 10:10
 * @describe JDBC 事务，直接利用 JDBC 的 commit、rollback。依赖于数据源获得的连接来管理事务范围。
 **/
@SuppressWarnings("ALL")
public class JdbcTransaction implements Transaction {

    protected Connection connection;

    protected DataSource dataSource;

    protected boolean autoCommit;

    protected TransactionIsolationLevel level = TransactionIsolationLevel.NONE;


    public JdbcTransaction(DataSource dataSource, boolean autoCommit, TransactionIsolationLevel level) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
        this.level = level;
    }

    public JdbcTransaction(Connection connection) {
        this.connection = connection;
    }

    @Override
    public Connection getConnection() throws SQLException {
        //获取一个新的数据库连接实例
        connection = dataSource.getConnection();
        //设置当前数据库连接的事务隔离级别
        connection.setTransactionIsolation(level.getLevel());
        //控制数据库连接的自动提交行为
        connection.setAutoCommit(autoCommit);
        return connection;
    }

    @Override
    public void commit() throws SQLException {
        if(Objects.nonNull(connection) && !connection.getAutoCommit()){
            connection.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if(Objects.nonNull(connection) && !connection.getAutoCommit()){
            connection.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if (connection != null && !connection.getAutoCommit()) {
            connection.close();
        }
    }
}